package tools.vetorial;

import java.awt.Graphics2D;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;

import core.DrawContext;
import core.Object2D;
import core.OurGraphics;
import core.VectorialObject;
import core.VectorialObject.DrawStyle;

public class VectorialRectTool extends PointSelectionTool {

	private VectorialRectProxy mProxy = new VectorialRectProxy();

	private VectorialObject mObject;
	
	private Point2D.Double mProxyPt = new Point2D.Double();
	
	@Override
	public void addPoint(int x, int y, int order, DrawContext ctx) {
		
		if(order%2 == 0) {
			mObject.addVertice(new Point2D.Double(x, y));
		}
		else {
			Point2D.Double firstPt = mObject.getVertice(0);
			
			mObject.addVertice(new Point2D.Double(x, firstPt.y));
			mObject.addVertice(new Point2D.Double(x, y));
			mObject.addVertice(new Point2D.Double(firstPt.x, y));
			
			pencilUp(ctx);
			pencilDown(ctx);
		}
		
	}

	@Override
	public Object2D getProxy() {
		return mProxy;
	}

	@Override
	public void pencilDown(DrawContext ctx) {
		mObject = new VectorialObject(DrawStyle.CLOSED);
	}

	@Override
	public void pencilUp(DrawContext ctx) {
		if(mObject.getVerticeCount() == 4) {
			ctx.addObject2d(mObject);
		}
		mObject = null;
	}

	@Override
	public void updateProxy(int x, int y, DrawContext ctx) {
		mProxyPt.x = x;
		mProxyPt.y = y;
	}
	
	private class VectorialRectProxy implements Object2D {

		private Rectangle2D.Double rect = new Rectangle2D.Double();
		
		@Override
		public void draw(OurGraphics g2) {
			
			if(mObject == null || mObject.getVerticeCount() == 0) {
				return;
			}
			
			Point2D.Double pt1 = mObject.getVertice(0);
			
			rect.x = pt1.x;
			rect.y = pt1.y;
			rect.width = Math.abs(pt1.x - mProxyPt.x);
			rect.height = Math.abs(pt1.y - mProxyPt.y);
			
			g2.getRealGraphics().draw(rect);
		}
		
	}

}
